import React, { useReducer, createContext } from 'react';
import isEqual from 'lodash/isEqual';
import { isString } from 'lodash';
// import { serialize } from './utils';
// import { source, target } from './settings';

// 1. 创建全局的Context
const Context = createContext();

export default Context;

// 2. 创建全局的Reducer
const initState = {
  targetNodePath: null, // 属性路径
  sourceNodePath: null, // 不是属性路径，后端返回的规则
  sourceFormat: 'JSON',
  targetFormat: 'JSON',
  previewMode: false, // 预览模式
};

function reducer(state, action) {
  const { type, payload } = action;

  if (type === 'toggle_preview_mode') {
    return {
      ...state,
      previewMode: !state.previewMode,
    };
  }

  if (type === 'update') {
    return {
      ...state,
      ...payload,
    };
  }

  if (type === 'quick_mapping_record_source') {
    const { sourceNodePath: newSourceNodePath = [] } = payload;
    const { sourceNodePath: oldSourceNodePath, targetNodePath: oldTargetNodePath } = state;

    // 取消
    if (isEqual(newSourceNodePath, oldSourceNodePath)) {
      return {
        ...state,
        sourceNodePath: null,
      };
    }

    // 凑齐一对映射成功
    if (isString(oldTargetNodePath) && Array.isArray(newSourceNodePath)) {
      return {
        ...state,
        targetNodePath: null,
        sourceNodePath: null,
      };
    }

    return {
      ...state,
      sourceNodePath: newSourceNodePath,
    };
  }

  if (type === 'quick_mapping_record_target') {
    const { targetNodePath: newTargetNodePath = '' } = payload;
    const { sourceNodePath: oldSourceNodePath, targetNodePath: oldTargetNodePath } = state;

    // 取消
    if (newTargetNodePath === oldTargetNodePath) {
      return {
        ...state,
        targetNodePath: null,
      };
    }

    // 凑齐一对，映射成功
    if (isString(newTargetNodePath) && Array.isArray(oldSourceNodePath)) {
      return {
        ...state,
        targetNodePath: null,
        sourceNodePath: null,
      };
    }

    return {
      ...state,
      targetNodePath: newTargetNodePath,
    };
  }

  throw new Error();
}

// 3. 将全局useReducer返回的state和dispatch传递给全局Context.Provider的value中
export const Provider = ({ children, value = {} }) => {
  const [state, dispatch] = useReducer(reducer, { ...initState, previewMode: value.readOnly });

  return (
    <Context.Provider value={{ state: { ...state, ...value }, dispatch }}>
      {children}
    </Context.Provider>
  );
};
